package com.hontlong.aixue.web;

import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hontlong.aixue.bean.Role;
import com.hontlong.aixue.bean.User;
import com.hontlong.aixue.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	private final Logger logger = org.slf4j.LoggerFactory
			.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@RequestMapping(method = RequestMethod.GET)
	public String login() {
		logger.debug("login()");
		return "user/login";
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		logger.debug("register() get");
		return "user/register";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String register(User user, Model model) {
		logger.debug("register() post");
		// BindingResult result,
		// new UserValidator().validate(user, result);
		// if (result.hasErrors()) {
		// model.addAttribute("user", user);
		// return "user/register";
		// }
		Role role = new Role();
		role.setRolename("ROLE_USER");
		Set<Role> roles = new HashSet<Role>();
		roles.add(role);

		user.setRoles(roles);

		this.userService.addUser(user);
		model.addAttribute("message", "注册用户成功");
		return "message";
	}

	@RequestMapping(value = "/{username}", method = RequestMethod.GET)
	public ModelAndView userHome(@PathVariable String username, ModelMap model) {
		model.addAttribute("username", username);
		return new ModelAndView("user/home",model);
	}
}
